<?php
/**
 * This file contains the class MemberModel which provides
 * most of the code requirements for the Member page
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    $Id:$
 * @link       http://my-trac.assembla.com/amemorytree/ticket/??
 * @since      File available since Release 0.1
 */
/**
 * This class provides the code for the Member page
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    Release: @package_version@
 * @link       http://my-trac.assembla.com/amemorytree/ticket/??
 * @since      Class available since Release 0.1
 */
class MemberModel
{
    /**
     * Access to the database methods
     *
     * @var MemberDB
     */
    private $_db;
    /**
     * Access to the View methods
     *
     * @var MemberView
     */
    private $_view;
    /**
     * Create a new instance of this class
     *
     * @return void
     * @param MemberDB $db
     * @param MemberView $view
     */
    public function __construct($db, $view)
    {
        $this->_db = $db;
        $this->_view = $view;
    }
    /**
     * Return an encrypted form of a string
     *
     * @return string
     * @param string $str
     */
    function encrypt($str)
    {
        return crypt($str, 'm3m0ry7r33');
    }
    /**
     * Check if the password was used to create the passCode
     *
     * @return bool
     * @param string $password
     * @param string $passCode
     */
    function isValidPassword($password, $passCode)
    {
        $isValid = crypt($password, $passCode) === $passCode;
        return $isValid;
    }
    /**
     * Check if the password is valid for the given user id
     *
     * @return bool
     * @param int $userId
     * @param string $password
     */
    function checkPassword($userId, $password)
    {
        $db = $this->_db;
        $passCode = $db->getPassword($userId);
        $isValid = $this->isValidPassword($password, $passCode);
        return $isValid;
    }
    /**
     * Login the user
     *
     * @return string
     * @param string $username
     * @param string $password
     */
    function loginUser($username, $password)
    {
        $db = $this->_db;
        $view = $this->_view;
        $message = '';
        $userId = $db->getUserId($username);
        $validPassword = $this->checkPassword($userId, $password);
        if ($validPassword) {
            $_SESSION['user'] = $userId;
        } else {
            $message .= $view->text('loginFailed');
        }
        return $message;
    }
    /**
     * Reset the session variables relating to the user login back to their default values
     *
     * @return bool
     * @param array[string]mixed &$session
     */
    function resetSession(&$session)
    {
        $session['user']="";
        $session['failLogin']=0;
    }
    /**
     * Change the password of a users account
     *
     * This change occurs only if the old password is correctly given, and
     * the new password correctly matches the duplicate confirmation password
     *
     * @return string
     * @param int $userId
     * @param array[string]mixed $passwords
     */
    function processNewPassword($userId, $passwords)
    {
        $db = $this->_db;
        $old = $db->escape($passwords['old']);
        $encrypted = $db->escape($passwords['encrypted']);
        $newPassword = $db->escape($passwords['new']);
        $confirmPassword = $db->escape($passwords['confirm']);
        $result = 'incorrect';
        if ($this->isValidPassword($old, $encrypted)) {
            if ($newPassword === $confirmPassword) {
                $db->setPassword($userId, $this->encrypt($newPassword));
                $result = 'changed';
            } else {
                $result = 'unchanged';
            }
        }
        return $result;
    }
    /**
     * Change a users password
     *
     * @return string
     * @param array[string]mixed &$session
     * @param mixed $oldPass
     * @param mixed $newPass
     * @param mixed $confirmPass
     */
    function changePassword(&$session, $oldPass, $newPass, $confirmPass)
    {
        $db = $this->_db;
        $userId = intval($session['user']);
        $passwordResult = $this->processNewPassword($userId, array(
            'encrypted' => $db->getPassword($userId),
            'old' => $db->escape($oldPass),
            'new' => $db->escape($newPass),
            'confirm' => $db->escape($confirmPass)
            )
        );
        return $passwordResult;
    }
    /**
     * Convert the permissions, provided as a CSV list, into a series of links
     *
     * @return string
     * @param string $permissions
     */
    function permissionLinks($permissions)
    {
        $view = $this->_view;
        $links = '';
        $permissionList = explode(',', $permissions);
        foreach ($permissionList as $permission) {
            switch ($permission) {
                case "Admin Area":
                    $links .= $view->text('adminControlLink');
                    $links .= '<br />';
                    break;
                case "FD Submit":
                    $links .= $view->text('addListingHeading');
                    $links .= $view->text('addListingLink');
                    $links .= '<br />';
                    $links .= $view->text('historyHeading');
                    $links .= $view->text('historyLink');
                    $links .= '<br />';
                    break;
                default:
            }
        }
        return $links;
    }
    /**
     * Show the member options page
     *
     * @return string
     * @param int $userId
     * @param string $changePasswordMessage
     */
    function memberOptions($userId, $changePasswordMessage)
    {
        $db = $this->_db;
        $view = $this->_view;
        $permissions = $db->getFuneralHomePermissions($userId);
        $permissionLinks = $this->permissionLinks($permissions);
        $alertLinks = $view->text('alertsHeading').$view->text('addAlertsLink').$view->text('manageAlertsLink').'<br />';
        $contactLinks = $view->text('memberContactHeading');
        $isFuneralDirector = preg_match('/FD Submit/', $permissions) === FALSE;
        if ($isFuneralDirector) {
            $contactLinks .= $view->text('deathNoticeContactLink');
        }
        $contactLinks .= $view->text('adminContactLink').$view->text('feedbackContactLink').'<br />';
        $optionLinks = $view->text('optionsHeading').$view->text('passwordLink').'<br />';
        $logoutForm = $view->logoutForm();
        $text = $view->memberOptions($permissionLinks, $alertLinks, $contactLinks, $optionLinks, $logoutForm);
        return $text;
    }
    /**
     * Show the welcome message
     *
     * @return string
     * @param int $userId
     */
    function welcome($userId)
    {
        $db = $this->_db;
        $view = $this->_view;
        $name = $db->getFuneralHomeName($userId);
        if (empty($name)) {
            $name = $db->getUsername($userId);
        }
        return $view->welcome($name);
    }
    /**
     * Show the change password form
     *
     * @return string
     * @param string $message
     */
    function changePasswordForm($message)
    {
        $view = $this->_view;
        $text = $message;
        $text .= $view->changePasswordForm();
        return $text;
    }
    /**
     * Show the member options page
     *
     * @return string
     * @param int $userId
     * @param string $changePasswordMessage
     * @param bool $showOptions
     */
    function memberPage($userId, $changePasswordMessage, $showOptions)
    {
        $db = $this->_db;
        $text = $this->welcome($userId);
        if ($showOptions) {
            $text .= $this->changePasswordForm($changePasswordMessage);
        }else{
            $text .= $this->memberOptions($userId, $changePasswordMessage);
        }
        return $text;
    }
    /**
     * Show the user login page
     *
     * @return string
     * @param int $userId
     * @param string $returnPath
     */
     function userLogin($userId, $returnPath)
    {
        $db = $this->_db;
        $view = $this->_view;
        $text = '';
        if (!empty($returnPath)) {
            $_SESSION['return'] = $returnPath;
        }
        $username = $db->getUsername($userId);
        $text .= $view->loginForm($username);
        return $text;
    }
}

?>